package com.example.smartcity.ui.newS

import android.app.ActionBar.LayoutParams
import android.content.Context
import android.content.Intent
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import android.text.Html
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.ArrayAdapter
import android.widget.LinearLayout
import androidx.core.view.get
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.bumptech.glide.Glide
import com.example.smartcity.R
import com.example.smartcity.SmartCityApplication
import com.example.smartcity.databinding.FragmentNewsBinding
import com.example.smartcity.logic.utils.Display.Companion.getHeight
import com.example.smartcity.logic.utils.Toast.Companion.showToast
import com.example.smartcity.ui.AcNews.NewSFlashShowActivity
import com.example.smartcity.ui.AcNews.SeekActivity
import com.example.smartcity.ui.home.fragment.*
import com.example.smartcity.ui.home.model.NewSRecyclerViewEntity
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator
import kotlinx.coroutines.flow.combine

class NewsFragment : Fragment() {

    private val viewModel by lazy {
        ViewModelProvider(this)[NewsViewModel::class.java]
    }

    private lateinit var binding: FragmentNewsBinding


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentNewsBinding.inflate(inflater, container, false)
        val root: View = binding.root

        // 轮播图
        newSBanner(binding.root, this)
        
        // 新闻专栏
        newS(binding.root)

        // 实现模糊查询
        setSeek()

        return root
    }

    private fun setSeek() {
        binding.NewsEdittext.setOnEditorActionListener { view, i, keyEvent ->
            if (i == EditorInfo.IME_ACTION_SEARCH){
                // 跳转至新闻搜索页面
                startActivity(Intent(binding.root.context, SeekActivity::class.java).apply {
                    putExtra("content", binding.NewsEdittext.text.toString())
                })
            }
            false
        }
    }


    /**
     * 轮播图
     */
    private fun newSBanner(view: View, a: LifecycleOwner){
        // 存储照片
        val array = ArrayList<String>()

        // 提交网络请求
        viewModel.slideshow(mutableMapOf<String, Int>().apply {
            this["pageNum"] = 1
            this["pageSize"] = 8
            this["type"] = 2
        })

        // 获取数据
        viewModel.slideshowLiveData.observe(this, Observer { resources ->
            val body = resources.getOrNull()
            if(body != null) {
                // 清空数据
                viewModel.slideshowList.clear()
                // 添加数据
                viewModel.slideshowList.addAll(body)
            }

            // 取出数据
            for (i in viewModel.slideshowList){
                if (array.size < viewModel.slideshowList.size) {
                    array.add(SmartCityApplication.url + i.advImg)
                }
            }

            // 轮播图圆角设置
            binding.newSBanner.setBannerRound(35F)
            // 适配器
            binding.newSBanner.setAdapter(object : BannerImageAdapter<String>(array){
                override fun onBindView(
                    holder: BannerImageHolder?,
                    data: String?,
                    position: Int,
                    size: Int
                ) {
                    // 设置图片加载
                    data?.let {
                        holder?.let {
                            Glide.with(view)
                                .load(data)
                                .into(holder.imageView)
                        }
                    }
                }
            }).addBannerLifecycleObserver(a).indicator = CircleIndicator(context)

            binding.newSBanner.setOnBannerListener { data, position ->
                val intent = Intent(context, NewSFlashShowActivity::class.java)
                intent.putExtra("model", position.toString())
                startActivity(intent)
            }
        })



        // 将视图显示出来
        binding.isBannner.visibility = View.VISIBLE
    }



    /**
     * TODO 获取新闻专栏
     */
    private fun newS(view: View){
        // 获取新闻专栏
        val tab = view.findViewById<TabLayout>(R.id.home_TabLayout)
        val vp = view.findViewById<ViewPager2>(R.id.homenews_viewPager2)


        // 设置TabLayout可以滑动
        tab.tabMode = TabLayout.MODE_SCROLLABLE
        // ViewPager适配器
        vp.adapter = object : FragmentStateAdapter(this){
            override fun getItemCount() = 6

            override fun createFragment(position: Int): Fragment = when(position){
                0 -> fragment1()
                1 -> fragment2()
                2 -> fragment3()
                3 -> fragment4()
                4 -> fragment5()
                else -> fragment6()
            }
        }
        // 设置TabLayout标题
        TabLayoutMediator(tab, vp){ tab, position ->
            when(position){
                0 -> tab.text = SmartCityApplication.title1
                1 -> tab.text = SmartCityApplication.title2
                2 -> tab.text = SmartCityApplication.title3
                3 -> tab.text = SmartCityApplication.title4
                4 -> tab.text = SmartCityApplication.title5
                else -> tab.text = SmartCityApplication.title6
            }
        }.attach()


        // 将界面显示出来
        binding.hotNews.visibility = View.VISIBLE
    }
}